/** 加载工作 */
<template>
    <div>
        <el-card class="box-card">
            <div slot="header" class="clearfix" style="text-align: center; font-weight: bolder">
                <el-page-header @back="goBack">
                    <span slot="content" style="position: absolute;left: 50%;">加载工作</span>
                </el-page-header>
            </div>
            <el-row class="title">工作项信息加载</el-row>
            <el-form ref="form" :model="form" label-width="auto" :rules="FormRules" label-suffix=":" style="width: 80%; margin: 24px auto 0 auto">
                <el-form-item label="督办工作excel文件上传" style="margin-left: 78px;">
                    <el-upload class="upload-excel" :limit="1" action="http://172.16.93.106:8090/api/dualTable/insertDualJobByExcel" :data="{userId:'18926090104',rowNum:form.ExcelRow}" :on-success="handleSuccess" :before-upload="beforeUpload"  accept=".xlsx, .xls">
                    <!-- <el-upload class="upload-excel" :limit="1" action="" :http-request="uploadFile" :before-upload="beforeUpload"  accept=".xlsx, .xls"> -->
                        <el-button size="small" icon="el-icon-upload" plain style="width: 250px;">选择工作文件（Excel）</el-button>
                    </el-upload>
                    <el-link :underline="false" type="primary" style="position: absolute;top: 0; left: 260px;">下载工作督办模板.xlsx</el-link>
                </el-form-item>

                <el-row>
                  <el-col :span="12">
                    <!-- 工作名称 -->
                     <el-form-item label="工作名称" prop="jobName">
                         <el-input v-model="form.jobName" size="small" placeholder="请输入工作名称"></el-input>
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="表格列头" label-width="110px">
                         <el-input v-model="form.ExcelRow" size="small" placeholder="请输入excel列头"></el-input>
                     </el-form-item>
                  </el-col>
                </el-row>

                <!-- 任务描述 -->
                <el-row style="margin-left: 65px;">
                   <el-col :span="6">
                        <el-form-item label="任务描述" label-width="100px" prop="jobContent">
                          <!-- <el-input v-model="form.jobContent" size="small" style="width:160px;" placeholder="请输入任务描述"></el-input> -->
                          <el-select size="small" v-model="form.jobContent" placeholder="任务描述">
                            <el-option v-for="(item, index) of selectList" :key="index" :label="item.label" :value="item.value"></el-option>
                          </el-select>
                        </el-form-item>
                   </el-col>
                  <el-col :span="6">
                      <el-form-item label="开始时间"  label-width="110px" prop="beginDateStr">
                         <!-- <el-date-picker v-model="form.beginDateStr" value-format="yyyy-MM-dd" type="date" size="small" placeholder="计划开始时间" style="width:150px;"></el-date-picker> -->
                         <el-select size="small" v-model="form.beginDateStr" placeholder="开始时间">
                            <el-option v-for="(item, index) of selectList" :key="index" :label="item.label" :value="item.value"></el-option>
                          </el-select>
                      </el-form-item>
                   </el-col>
                   <el-col :span="6">
                      <!-- 完成时间 -->
                    <el-form-item label="完成时间" label-width="110px" prop="planOverDateStr">
                       <!-- <el-date-picker v-model="form.planOverDateStr" value-format="yyyy-MM-dd" type="date" size="small" style="width:150px;" placeholder="计划结束时间"></el-date-picker> -->
                       <el-select size="small" v-model="form.planOverDateStr" placeholder="完成时间">
                          <el-option v-for="(item, index) of selectList" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                  </el-col>
                   <el-col :span="6">
                    <el-form-item label="负责人" label-width="100px" prop="principalId">
                      <el-select size="small" v-model="form.principalId" placeholder="责任部门">
                          <!-- <el-option label="配资部" value="配资部"></el-option>
                          <el-option label="安监部" value="安监部"></el-option>
                          <el-option label="配网部" value="配网部"></el-option> -->
                          <el-option v-for="(item, index) of selectList" :key="index" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                   </el-col>
               </el-row>

                <el-form-item label="定期督办">
                  <el-radio-group v-model="form.errorType">
                      <el-radio :label="0">时</el-radio>
                      <el-radio :label="1">天</el-radio>
                      <el-radio :label="2">周</el-radio>
                      <!-- <el-radio v-for="(item, index) of selectList" :key="index" :label="item.value">{{ item.label }}</el-radio> -->
                  </el-radio-group>
                  <span class="errorTypeInput" v-show="form.errorType == 0">
                    每隔 <el-input-number size="mini" v-model="errorHour" :controls="false" :min="1" :max="99"
                        style="width: 50px;"></el-input-number> 小时发送提醒
                  </span>
                  <span class="errorTypeInput" v-show="form.errorType == 1">
                    每隔 <el-input-number size="mini" v-model="errorDay" :controls="false" :min="1" :max="99"
                        style="width: 50px;"></el-input-number> 天，在 <el-input-number size="mini" v-model="errorHour" :controls="false" :min="0" :max="23"
                        style="width: 50px;"></el-input-number> 点钟发送提醒
                  </span>
                  <span class="errorTypeInput" v-show="form.errorType == 2">
                    每隔 <el-input-number size="mini" v-model="errorWeek" :controls="false" :min="1" :max="99"
                        style="width: 50px;"></el-input-number> 周，在周 <el-input-number size="mini" v-model="errorDay" :controls="false" :min="1" :max="5"
                        style="width: 50px;"></el-input-number> 的 <el-input-number size="mini" v-model="errorHour" :controls="false" :min="0" :max="23"
                        style="width: 50px;"></el-input-number> 点钟发送提醒
                  </span>
                </el-form-item>
                <el-form-item label="预警时限">
                    <span class="foneSizeClolor">距离完成时间</span>
                    <el-input-number size="mini" v-model="form.errorDay" :controls="false" :max="99"
                        style="width: 50px;"></el-input-number>
                    <span class="foneSizeClolor">天时报警，展示到“红灯区模块”</span>
                </el-form-item>
                <el-form-item>
                    <!-- <el-button type="primary" @click="onSubmit">立即创建</el-button>
                    <el-button>取消</el-button> -->
                    <!-- 删除按钮 -->
                    <!-- <i class="el-icon-delete" style="float: right;"></i> -->
                </el-form-item>
            </el-form>
            <!-- 保存及发布按钮-->
            <el-row class="end">
              <el-button type="info" size="small" @click="onSubmit">保存工作</el-button>
              <el-button type="primary" size="small" @click="setWork">发布工作</el-button>
            </el-row>
        </el-card>
    </div>
</template>

<script>
// 引入时间函数
import utils from "@/utils/util";
import * as calculateTimePoint from "@/utils/calculateTimePoint.js"
import { testAPI, insertJobAPI, insertDualJobByExcelAPI, testData, insertListBydualAPI  } from "../api/user.js"
export default {
    name: "LoadWork",
    data() {
        return {
            form: {
                jobName: "",  // 工作名称
                jobContent: "",   // 任务描述
                beginDateStr: "",   // 计划开始时间
                planOverDateStr: "",  // 计划完成时间
                principalId:"",   // 任务负责人id principalName
                errorType: 0,    // 定期督办类型
                ExcelRow:1,
                errorDay:"1"        // 预警时限
            },
            // 定期督办要计算时间的参数
            errorHour: 0,
            errorDay: 1,
            errorWeek: 1,
            // 获取上传的文件名
            filename:"暂无数据",
            // 表单校验
            FormRules:{
              jobName: [
                { required: true, message: '请输入工作名称', trigger: 'blur' }
              ],
              jobContent: [
                { required: true, message: '请选择任务描述', trigger: 'blur' }
              ],
              beginDateStr: [
                { required: true, message: '请选择开始时间', trigger: 'blur' }
              ],
              planOverDateStr: [
                { required: true, message: '请选择结束时间', trigger: 'blur' }
              ],
              principalId: [
                { required: true, message: '请选择负责人', trigger: 'blur' }
              ],
            },
            selectList: [],
            dualInfoId: ""
        };
    },
    created() {
    },
    methods: {
        haha() {
            this.dualInfoId = testData.dualInfoId
            for (let i = 1; i <= 30; i++) {
              //console.log(testData["column" + i])
              if(testData["column" + i] != null) {
                this.selectList.push({
                  label: testData["column" + i],
                  value: "getColumn" + i
                })
              }
            }
            console.log(this.selectList)
        },
        goBack() {
            this.$router.back()
        },
        // 文件上传之前的钩子函数
        beforeUpload(file) {
          console.log(file);
          this.filename = file.name
          this.selectList = []
        },
        // 文件上传之后
        handleSuccess(res) {
          console.log("上传成功", res)
          this.dualInfoId = res.dualInfoId
          this.form.jobName = res.excelName.replace(/\.(xlsx|xls)$/, '')
            for (let i = 1; i <= 30; i++) {
              if(res["column" + i] != null) {
                this.selectList.push({
                  label: res["column" + i],
                  value: "getColumn" + i
                })
              }
            }
            console.log(this.selectList)
            this.$message.success("上传成功")
          // console.log("上传成功", res)

        },
        // 上传接口
        uploadFile(e) {
          return console.log(e)
          //const formData = new FormData()
          //formData.append("file", e.file)
          //formData.append("userId", 1)
          insertDualJobByExcelAPI({
            file: e.file,
            userId: 1,
            rowNum: 1
          }).then(res => {
            console.log(res)
          }).catch(fail => {
            console.log(fail)
          })
        },
        // 保存
        onSubmit() {
           // 保存这边需要先校验然后才能进行数据的创建
            this.$refs.form.validate((valid) => {
              if (valid) {
                 console.log("校验成功!!!")
                 console.log(this.form)
               }
            });
        },
        // 发布
        setWork() {
           const loadingInstance = this.$loading()
           let time = ""
           switch (this.form.errorType) {
            case 0:
              time = calculateTimePoint.getNextTimePointHour(this.errorHour);
              break;
            case 1:
              time = calculateTimePoint.getNextTimePointDay(this.errorDay, this.errorHour, new Date())
              break;
            case 2:
              time = calculateTimePoint.getNextTimePointWeek(this.errorWeek, this.errorDay, this.errorHour, new Date());
              break;
            default:
              break;
           }
           console.log("发布")
           this.$refs.form.validate((valid) => {
             if (valid) {
                 console.log("校验成功!!!")
                 console.log(this.form)
                 let data = {
                  ...this.form,
                  excelName: this.form.jobName,
                  dualInfoId: this.dualInfoId,
                  jobState: 1,    // 工作状态
                  nextDate: utils.Dateformat(time,"yyyy-MM-dd HH:mm"),
                  createName: "沈华洲",
                  creatorId: "18926090104",
                 }
                 delete data.ExcelRow
                 data.principalName = data.principalId
                 insertListBydualAPI(data).then(res => {
                  console.log(res)
                  loadingInstance.close()
                  this.$message.success("创建成功")
                  this.goBack()
                 }).catch(fail => {
                  loadingInstance.close()
                  console.log(fail)
                 })
                 //bus传值 =====> 注意把异步改成同步
                // this.$nextTick(() => {
                //   this.$bus.$emit('getFormData', {...this.form});
                // });

                // //页面跳转
                // this.$router.push({
                // name: 'WorkBoard',
                // });
                // this.$message({
                  // message: '成功发布了一条工作数据',
                  // type: 'success'
                // });
              }
           });
        },
        numInput(e) {
            console.log(e);
        }
    },
};
</script>

<style scoped lang="less">
.body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

.el-header {
    background-color: #b3c0d1;
    color: #333;
    line-height: 60px;
}

.el-aside {
    color: #333;
}

.title {
    font-weight: bolder;
    padding-left: 12px;
    border-left: 6px solid #3975C6;
}
.fileList {
  position: absolute;
  top: 0;
  left: 260px;
  width: 500px;
}

/deep/.el-form-item__label {
  padding-right: 10px;
}

.end {
   display: flex;
   justify-content:flex-end;
}

.foneSizeClolor {
  color: #2b6df2;
}
.errorTypeInput {
  margin-left: 50px;
}
</style>
